/**
 * 工作项查询表单组件
 */

'use client';

import React from 'react';
import {
  Form,
  Input,
  Select,
  DatePicker,
  Button,
  Space,
  Card,
  Row,
  Col,
  Tag,
} from 'antd';
import {
  SearchOutlined,
  ReloadOutlined,
  ClearOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import type { WorkItemQueryParams } from '../types/workItem';
import { useProjects, useWorkItemMeta } from '../hooks/useWorkItems';

const { Option } = Select;
const { RangePicker } = DatePicker;

interface WorkItemQueryFormProps {
  onSearch: (params: WorkItemQueryParams) => void;
  loading?: boolean;
  initialValues?: WorkItemQueryParams;
}

export default function WorkItemQueryForm({
  onSearch,
  loading = false,
  initialValues,
}: WorkItemQueryFormProps) {
  const [form] = Form.useForm();
  const { projects } = useProjects();
  const selectedProjectId = Form.useWatch('project_id', form);
  const { types, states, priorities, users } = useWorkItemMeta(selectedProjectId);
  // 获取所有用户数据，而不依赖于项目选择
  const { users: allUsers } = useWorkItemMeta();

  // 设置默认创建时间范围为最近一个月
  const getDefaultCreatedRange = () => {
    const end = dayjs().endOf('day');
    const start = end.subtract(1, 'month').startOf('day');
    return [start, end];
  };

  const handleSearch = () => {
    const values = form.getFieldsValue();
    
    // 处理日期范围
    const params: WorkItemQueryParams = { ...values };
    
    if (values.dateRange) {
      params.start_date = values.dateRange[0]?.format('YYYY-MM-DD');
      params.end_date = values.dateRange[1]?.format('YYYY-MM-DD');
      delete params.dateRange;
    }

    if (values.createdRange) {
      const start = values.createdRange[0]?.startOf('day').unix();
      const end = values.createdRange[1]?.endOf('day').unix();
      params.created_between = `${start},${end}`;
      delete params.createdRange;
    }

    if (values.updatedRange) {
      const start = values.updatedRange[0]?.startOf('day').unix();
      const end = values.updatedRange[1]?.endOf('day').unix();
      params.updated_between = `${start},${end}`;
      delete params.updatedRange;
    }

    // 移除空值
    Object.keys(params).forEach(key => {
      const value = params[key as keyof WorkItemQueryParams];
      if (value === undefined || value === null || value === '') {
        delete params[key as keyof WorkItemQueryParams];
      }
    });

    // 确保重置到第一页
    params.page_index = 1;

    onSearch(params);
  };

  const handleReset = () => {
    form.resetFields();
    // 重置时也要确保从第一页开始，并使用默认页面大小
    onSearch({ page_index: 1, page_size: 100 });
  };

  const getTypeTag = (type: string) => {
    const typeMap: Record<string, { color: string; text: string }> = {
      epic: { color: 'purple', text: '史诗' },
      feature: { color: 'blue', text: '特性' },
      story: { color: 'green', text: '用户故事' },
      task: { color: 'orange', text: '任务' },
      bug: { color: 'red', text: '缺陷' },
      issue: { color: 'gray', text: '事务' },
    };
    const config = typeMap[type] || { color: 'default', text: type };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  return (
    <Card 
      title="查询条件" 
      size="small"
      styles={{ body: { paddingBottom: 8 } }}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          ...initialValues,
          createdRange: getDefaultCreatedRange()
        }}
        onFinish={handleSearch}
      >
        <Row gutter={[12, 8]}>
          {/* 第一行：主要查询条件 */}
          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="项目" name="project_id" style={{ marginBottom: 8 }}>
              <Select
                placeholder="选择项目"
                allowClear
                showSearch
                size="small"
                optionFilterProp="children"
                filterOption={(input, option) =>
                  String(option?.label || option?.children || '').toLowerCase().includes(input.toLowerCase())
                }
              >
                {projects.map(project => (
                  <Option key={project.id} value={project.id}>
                    {project.name} ({project.identifier})
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="标题" name="title" style={{ marginBottom: 8 }}>
              <Input placeholder="搜索标题" allowClear size="small" />
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="编号" name="identifier" style={{ marginBottom: 8 }}>
              <Input placeholder="工作项编号" allowClear size="small" />
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="类型" name="type" style={{ marginBottom: 8 }}>
              <Select placeholder="选择类型" allowClear size="small">
                {types.map(type => (
                  <Option key={type.id} value={type.id}>
                    {getTypeTag(type.id)} {type.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="状态" name="state_id" style={{ marginBottom: 8 }}>
              <Select placeholder="选择状态" allowClear size="small">
                {states.map(state => (
                  <Option key={state.id} value={state.id}>
                    <Tag color={state.color}>{state.name}</Tag>
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="优先级" name="priority_id" style={{ marginBottom: 8 }}>
              <Select placeholder="选择优先级" allowClear size="small">
                {priorities.map(priority => (
                  <Option key={priority.id} value={priority.id}>
                    {priority.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          {/* 第二行：次要查询条件 */}
          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label={`负责人 (${allUsers.length}个)`} name="assignee_id" style={{ marginBottom: 8 }}>
              <Select
                placeholder={allUsers.length === 0 ? "暂无用户数据" : "选择负责人"}
                allowClear
                showSearch
                size="small"
                optionFilterProp="children"
                filterOption={(input, option) => {
                  const children = String(option?.label || option?.children || '');
                  return children.toLowerCase().includes(input.toLowerCase());
                }}
                notFoundContent={allUsers.length === 0 ? "正在加载用户数据..." : "未找到匹配的用户"}
              >
                {allUsers.map(user => (
                  <Option key={user.id} value={user.id}>
                    {user.display_name} ({user.name})
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={4}>
            <Form.Item label="迭代" name="sprint_id" style={{ marginBottom: 8 }}>
              <Input placeholder="迭代ID" allowClear size="small" />
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={8} lg={5}>
            <Form.Item label="开始/结束时间" name="dateRange" style={{ marginBottom: 8 }}>
              <RangePicker
                format="YYYY-MM-DD"
                placeholder={['开始', '结束']}
                size="small"
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={8} lg={5}>
            <Form.Item label="创建时间" name="createdRange" style={{ marginBottom: 8 }}>
              <RangePicker
                showTime
                format="MM-DD HH:mm"
                placeholder={['创建开始', '创建结束']}
                size="small"
                style={{ width: '100%' }}
              />
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={3}>
            <Form.Item label="归档状态" name="is_archived" style={{ marginBottom: 8 }}>
              <Select placeholder="归档状态" allowClear size="small">
                <Option value={0}>未归档</Option>
                <Option value={1}>已归档</Option>
              </Select>
            </Form.Item>
          </Col>

          <Col xs={24} sm={12} md={6} lg={3}>
            <Form.Item label="每页显示" name="page_size" initialValue={100} style={{ marginBottom: 8 }}>
              <Select placeholder="每页数量" size="small">
                <Option value={20}>20条</Option>
                <Option value={50}>50条</Option>
                <Option value={100}>100条</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Row style={{ marginTop: 8 }}>
          <Col span={24}>
            <Space>
              <Button
                type="primary"
                icon={<SearchOutlined />}
                onClick={handleSearch}
                loading={loading}
                size="small"
              >
                查询
              </Button>
              <Button
                icon={<ClearOutlined />}
                onClick={handleReset}
                size="small"
              >
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </Form>
    </Card>
  );
}